<template>
  <div class="cmsUploadFile" :class="disabled?'noneBtn':''">
    <el-upload
      class="upload-demo fill span18 small-payment-upload"
      :before-upload="(file)=>uploadPartOne(file)"
      action
      :show-file-list="false"
      :before-remove="(file,fileListA)=>removeFile(file,fileListA,fileSystem.part)"
      :file-list="list"
      :disabled="disabled"
    >
      <div>
        <el-button v-if="!disabled"
                   size="small"
                   :loading="isLoading"
                   type="primary">
          <i class="iconfont icon-shangchuan"></i> 点击上传
        </el-button>

      </div>

      <div slot="tip" v-if="!disabled" class="el-upload__tip" style="line-height: 20px!important;">{{info}}</div>
    </el-upload>
    <div class="file" >
      <div v-for="(item,index) in list" :key="index" :style="{display:phoneState?'black':'flex'}" class="fileList">
        <el-tooltip effect="dark"
                    :content="item.realName"
                    placement="top-start">
          <div class="fileName" @click="preview(item)">
            <span :class='isOlder ? "realName" : ""'><i class="bg"></i>{{item.realName}}</span>
          </div>
        </el-tooltip>
        <div>
          <slot name="button" :scope="{file:item,index:index}"></slot>
          <el-button @click="download(item)" type="primary" :size="isOlder ? 'medium' : 'mini'" round icon='el-icon-download'>下载</el-button>
          <el-button @click="removeFile(item)" type="danger" :size="isOlder ? 'medium' : 'mini'" v-show="!disabled" round icon='el-icon-delete'>删除</el-button>
        </div>
      </div>
      <div v-for="(item,index) in addList" :key="index"  :style="{display:phoneState?'black':'flex'}" class="fileList">
        <el-tooltip effect="dark"
                    :content="item.name"
                    placement="top-start">
          <div class="fileName">
            <span><i class="bg"></i>{{item.name}}</span>
          </div>
        </el-tooltip>
        <div>
          <slot name="button" :scope="{file:item,index:index}"></slot>
          <el-button @click="removeFile(item)" type="danger" size="mini">删除</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { v4 as uuidv4 } from 'uuid';
  import msgUtil from '@/utils/msgUtil'
  import publicUpload from '@/utils/publicUpload'
  export default {
    name: "UploadFile",
    props: {
      isOlder: false,
      disabled: {
        type: Boolean,
        default: false
      },
      detailType: {
        type: String,
        default: ''
      },
      fileList: {
        type: Array,
        default: () => []
      },
      fileSystem: {
        type: Object,
        default: {
          sys: '',
          module: '',
          entityClass: '',
          viewByAnon: true,
          longLife: false,
          part: 'one'
        }
      },
      detailId: {
        type: String,
        default: ''
      },
      type: {
        type: String,
        default: 'single'
        //  mul--多文件，single---单文件
      },
      info: {
        type: String,
        default: ''
        //  文件支持类型
      },
      //文件類型校验方法-若需要校验，从父组件传入此方法
      checkFiles: {
        type: Function,
        default: (file) => {
          return true
        }
      },
      //获取文件后的回调函数-从父组件传入此方法
      getFilesCb: {
        type: Function,
        default: () => { }
      },
      //获取文件后的回调函数-从父组件传入此方法
      uploadCb: {
        type: Function,
        default: () => { }
      }
    },
    watch: {
      'fileList': {
        handler(val) {
          this.list = [...val]
        },
        deep: true
      },
      'detailId': {
        handler(val, oldVal) {
          this.init()
        },
        deep: true
      },
      isOlder(val) {
        this.isOlder = val
      }
    },
    data() {
      return {
        isLoading: false,
        list: [],
        addList: [],
        phoneState: false
      }
    },
    mounted() {
      this.init()
      if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i))) {
        this.phoneState = true
      } else {
        this.phoneState = false
      }
    },
    methods: {
      // 弹窗里面引用文件，需要销毁掉，防止数据串了。
      saveAll(formId) {
        this.addList.forEach(it => {
          this.upload(it, this.fileSystem.part, formId)
        })
        this.addList = []
      },
      init() {
        this.list = []
        publicUpload.getFile(this.fileSystem.module, this.detailId, this.fileSystem.part)
          .then(res => {
            const items = res.data || []
            const arr = []
            items.forEach(o => {
              arr.push({
                realName: o.name,
                name: o.name,
                size: o.size,
                id: o.id
              })
            })
            this.list = arr
            this.change()
          })
      },

      getFile(file) {
        publicUpload.checkFile(file.id)
      },
      uploadPartOne(file) {
        if (!this.checkFiles(file)) {
          return
        }
        this.addList.push(file)
        this.change()
      },
      // 上传文件前
      async upload(file, part, id) {
        if (!this.checkFiles(file)) {
          return
        }
        /*
        *公共上传方法
        * */
        this.$set(this, 'isLoading', true)
        let formId = id || this.detailId
        if (!formId) {
          msgUtil.error2('上传文件-表单编号不能为空！')
          return
        }
        await publicUpload.uploadFile(
          file,
          formId,
          this.fileSystem.module,
          part,
          file.name,
        )
          .then(async res => {
            if (res.code === 200) {
              if (this.type === 'single') {
                if (this.list.length != 0) {
                  //先解绑
                  await publicUpload.removeFile(this.list[0].id)
                  this.list = [{
                    realName: file.name,
                    name: file.name,
                    size: file.size,
                    id: res.data[0],
                  }]
                } else {
                  this.list = [{
                    realName: file.name,
                    name: file.name,
                    size: file.size,
                    id: res.data[0],
                  }]
                }
              }
              if (this.type === 'mul') {
                this.list.push({
                  realName: file.name,
                  name: file.name,
                  size: file.size,
                  id: res.data[0],
                })
              }
              this.uploadCb(res)
            } else {
              msgUtil.error2(res.data.message)
            }
          })
          .catch(res => {
            this.$set(this, 'isLoading', false)
            msgUtil.error2(this.$route.name + '上传文件前-请求失败')
          })
        this.$set(this, 'isLoading', false)
        this.change()
      },
      // 删除文件时解绑文件
      removeFile(file, fileList, part) {
        let isNew = false
        this.addList.forEach((item, index) => {
          if (file.id === item.id) {
            this.addList.splice(index, 1)
            isNew = true
          }
        })

        if (isNew) {
          this.change()
          return
        }

        if (this.type === 'mul') {
          this.list.forEach((item, index) => {
            if (file.id === item.id) {
              this.list.splice(index, 1)
            }
          })
        }
        if (this.type === 'single') {
          this.$set(this, 'list', [])
        }
        publicUpload.removeFile(file.id)
        this.change()
      },
      download(file) {
        publicUpload.checkFile(file.id, file.realName)
      },
      preview(file) {
        if (file.id) {
          publicUpload.filePreview(file.id)
        }
      },
      change() {
        this.$emit('change', this.list, this.addList)
      },
      uuid() {
        return uuidv4().split('-')[0]
      },
    }
  }
</script>

<style scoped lang="scss">
  .cmsUploadFile {
    /*width: 400px;*/
    .fileList {
      /*display: flex;*/
      align-items: center;
      justify-content: space-between;
      .fileName {
        display: flex;
        align-items: center;
        cursor: pointer;
        span {
          display: block;
          width: 247px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }
</style>
<style lang="scss">
  .noneBtn {
    .small-payment-upload {
      display: none;
    }
  }
  .realName {
    font-size: 18px;
  }
</style>
